<template>
  <view class="contact-info">
    <!-- 联系人姓名与分类 -->
    <view class="info-header">
      <!-- 姓名 - 点击编辑 -->
      <view class="name-wrapper" @tap="startEdit('name')">
        <view v-if="!isEditingField.name" class="contact-name">
          {{ currentContact?.name || '未设置' }}
          <text class="edit-icon">✎</text>
        </view>
        <input 
          v-else 
          class="name-input" 
          v-model="editingData.name" 
          focus 
          @blur="saveEdit('name')"
          @confirm="saveEdit('name')"
        />
      </view>
      
      <!-- 分类 - 点击编辑 (改为手动输入) -->
      <view class="category-wrapper" @tap="startEdit('category')">
        <view v-if="!isEditingField.category" class="contact-category">
          {{ currentContact?.category || '未分类' }}
          <text class="edit-icon">✎</text>
        </view>
        <input 
          v-else 
          class="category-input" 
          v-model="editingData.category" 
          focus 
          placeholder="请输入分类"
          @blur="saveEdit('category')"
          @confirm="saveEdit('category')"
        />
      </view>
    </view>

    <!-- 联系人信息表格 -->
    <view class="info-grid">
      <!-- 关系 - 点击编辑 -->
      <view class="info-item" @tap="startEdit('relation')">
        <text class="label">关系</text>
        <view class="value-wrapper">
          <text v-if="!isEditingField.relation" class="value">
            {{ currentContact?.relation || '未设置' }}
            <text class="edit-icon">✎</text>
          </text>
          <input 
            v-else 
            class="value-input" 
            v-model="editingData.relation" 
            focus
            placeholder="请输入关系"
            @blur="saveEdit('relation')"
            @confirm="saveEdit('relation')"
          />
        </view>
      </view>
      
      <!-- 生日 - 点击编辑 -->
      <view class="info-item" @tap="startEdit('birthday')">
        <text class="label">生日</text>
        <view class="value-wrapper">
          <text v-if="!isEditingField.birthday" class="value">
            {{ currentContact?.birthday || '未设置' }}
            <text class="edit-icon">✎</text>
          </text>
          <picker 
            v-else 
            mode="date" 
            :value="editingData.birthday" 
            @change="handleBirthdayChange"
          >
            <view class="date-picker">
              {{ editingData.birthday || '选择日期' }}
            </view>
          </picker>
        </view>
      </view>
    </view>
    
    <!-- 备注 - 点击编辑 -->
    <view class="info-item notes-item" @tap="startEdit('notes')">
      <text class="label">备注</text>
      <view class="value-wrapper">
        <text v-if="!isEditingField.notes" class="value">
          {{ currentContact?.notes || '无' }}
          <text class="edit-icon">✎</text>
        </text>
        <textarea 
          v-else 
          class="notes-input" 
          v-model="editingData.notes" 
          focus 
          placeholder="请输入备注"
          @blur="saveEdit('notes')"
        />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useContactStore } from '@/store/modules/contact';
import { useCategoryStore } from '@/store/modules/category';
import { Contact, Category } from '@/types';

const props = defineProps({
  contact: {
    type: Object as () => Contact | null,
    default: null
  },
  contactId: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['update:contact']);

const contactStore = useContactStore();
const categoryStore = useCategoryStore();

// 字段编辑状态
const isEditingField = ref({
  name: false,
  category: false,
  relation: false,
  birthday: false,
  notes: false
});

// 编辑中的数据
const editingData = ref({
  name: '',
  category: '',
  relation: '',
  birthday: '',
  notes: ''
});

// 获取联系人数据
const currentContact = computed(() => {
  // 如果props.contact存在则使用，否则从store获取
  if (props.contact) return props.contact;
  
  // 尝试从store获取联系人数据
  if (props.contactId) {
    return contactStore.getContactById(props.contactId);
  }
  return null;
});

// 监听联系人数据变化，自动更新编辑表单初始值
watch(currentContact, (newContact) => {
  if (newContact) {
    editingData.value.name = newContact.name || '';
    editingData.value.category = newContact.category || '';
    editingData.value.relation = newContact.relation || '';
    editingData.value.birthday = newContact.birthday || '';
    editingData.value.notes = newContact.notes || '';
  }
}, { immediate: true });

// 开始编辑字段
const startEdit = (field: 'name' | 'category' | 'relation' | 'birthday' | 'notes') => {
  // 重置所有编辑状态
  Object.keys(isEditingField.value).forEach(key => {
    isEditingField.value[key as keyof typeof isEditingField.value] = false;
  });
  
  // 设置当前编辑字段状态为true
  isEditingField.value[field] = true;
  
  // 初始化编辑数据
  if (currentContact.value) {
    switch(field) {
      case 'name':
        editingData.value.name = currentContact.value.name || '';
        break;
      case 'category':
        editingData.value.category = currentContact.value.category || '';
        break;
      case 'relation':
        editingData.value.relation = currentContact.value.relation || '';
        break;
      case 'birthday':
        editingData.value.birthday = currentContact.value.birthday || '';
        break;
      case 'notes':
        editingData.value.notes = currentContact.value.notes || '';
        break;
    }
  }
};

// 处理生日变更
const handleBirthdayChange = (e: any) => {
  editingData.value.birthday = e.detail.value;
  saveEdit('birthday');
};

// 保存编辑
const saveEdit = async (field: 'name' | 'category' | 'relation' | 'birthday' | 'notes') => {
  if (!currentContact.value) return;
  
  try {
    // 创建更新后的联系人对象
    const updatedContact = { ...currentContact.value };
    
    // 更新对应字段
    switch(field) {
      case 'name':
        updatedContact.name = editingData.value.name;
        break;
      case 'category':
        updatedContact.category = editingData.value.category;
        break;
      case 'relation':
        updatedContact.relation = editingData.value.relation;
        break;
      case 'birthday':
        updatedContact.birthday = editingData.value.birthday;
        break;
      case 'notes':
        updatedContact.notes = editingData.value.notes;
        break;
    }
    
    // 更新联系人数据
    await contactStore.updateContact(updatedContact);
    
    // 通知父组件数据已更新
    emit('update:contact', updatedContact);
    
    // 显示保存成功提示
    uni.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 1500
    });
    
    // 重置编辑状态
    isEditingField.value[field] = false;
  } catch (error) {
    console.error('保存联系人信息失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'error',
      duration: 1500
    });
  }
};
</script>

<style lang="scss">
.contact-info {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .info-header {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;
    
    .name-wrapper {
      flex: 1;
      
      .contact-name {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        margin-right: 20rpx;
        display: flex;
        align-items: center;
        
        .edit-icon {
          font-size: 24rpx;
          color: #999;
          margin-left: 10rpx;
          opacity: 0.5;
        }
        
        &:active {
          opacity: 0.7;
        }
      }
      
      .name-input {
        font-size: 36rpx;
        font-weight: bold;
        color: #333;
        border-bottom: 1px solid var(--primary-color);
        padding-bottom: 6rpx;
      }
    }
    
    .category-wrapper {
      .contact-category {
        font-size: 24rpx;
        color: var(--primary-color);
        background-color: var(--background-color);
        padding: 4rpx 12rpx;
        border-radius: 4rpx;
        display: flex;
        align-items: center;
        
        .edit-icon {
          font-size: 20rpx;
          color: #999;
          margin-left: 6rpx;
          opacity: 0.5;
        }
        
        &:active {
          opacity: 0.7;
        }
      }
      
      .category-input {
        font-size: 24rpx;
        color: var(--primary-color);
        background-color: var(--background-color);
        padding: 4rpx 12rpx;
        border-radius: 4rpx;
        border: 1px dashed var(--primary-color);
      }
    }
  }
  
  .info-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
    margin-bottom: 20rpx;
  }
  
  .info-item {
    &:active {
      opacity: 0.7;
    }
    
    .label {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 8rpx;
      display: block;
    }
    
    .value-wrapper {
      position: relative;
      
      .value {
        font-size: 28rpx;
        color: #333;
        display: flex;
        align-items: center;
        word-break: break-all;
        
        .edit-icon {
          font-size: 22rpx;
          color: #999;
          margin-left: 6rpx;
          opacity: 0.5;
        }
      }
      
      .value-input {
        font-size: 28rpx;
        color: #333;
        border-bottom: 1px solid var(--primary-color);
        padding-bottom: 4rpx;
        width: 100%;
      }
      
      .date-picker {
        font-size: 28rpx;
        color: #333;
        border-bottom: 1px solid var(--primary-color);
        padding-bottom: 4rpx;
        width: 100%;
      }
    }
  }
  
  .notes-item {
    margin-top: 10rpx;
    
    .notes-input {
      width: 100%;
      height: 100rpx;
      font-size: 28rpx;
      color: #333;
      border: 1px solid #eee;
      border-radius: 8rpx;
      padding: 10rpx;
      background-color: #f9f9f9;
    }
  }
}
</style> 